<template>
  <div class="layoutSidebar">
    <!-- <div class="emergency-ranks-hide" v-if="ifShow" @click="showBox"></div>
    <div class="emergency-ranks-show" v-else @click="showBox"></div>-->
    <div
      class="emergency-ranks"
      v-if="ifShow"
      v-loading="loading"
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <div class="emergency-ranks-title">
        <div class="emergency-ranks-title-text">卫生应急队伍</div>
      </div>
      <div class="emergency-ranks-search">
        <input
          type="text"
          v-model="searchValue"
          class="emergency-ranks-searchInput"
          placeholder="名称"
        />
        <span class="emergency-ranks-searchIcon" @click="getListData()"></span>
      </div>
      <ul class="emergency-ranks-ul" v-if="!loading">
        <el-scrollbar
          style="height: 100%;"
          class="cmp-scrollbar-y"
          v-if="showList.length"
        >
          <li
            class="emergency-ranks-list"
            v-for="(value, index) in showList"
            :key="index"
            @click="showDetails(value, index)"
            :class="{ activeLi: currentLi == index }"
          >
            <span
              class="emergency-ranks-list-edit"
              v-show="value.edit != true && filterLengentFlag"
              @click.stop="editCurrent(value, index)"
            ></span>
            <span
              class="emergency-ranks-list-save"
              v-show="value.edit == true && filterLengentFlag"
              @click.stop="saveCurrent(value, $event)"
            ></span>
            <input
              class="emergency-ranks-list-input"
              type="text"
              v-model.trim="value.teamname"
              v-show="value.edit == true"
              maxlength="20"
              @click.stop
              @blur="blurClass(value,index)"
            />
            <span
              class="emergency-ranks-list-name"
              v-show="value.edit != true"
              :title="value.teamname"
              >{{ value.teamname }}</span
            >
            <span
              class="emergency-ranks-list-position"
              v-show="value.edit == true"
              @click.stop="resetPosition()"
            ></span>
          </li>
        </el-scrollbar>
        <li class="emergency-ranks-list-nodata" v-if="!showList.length">
          暂无数据
        </li>
      </ul>
      <div class="emergency-ranks-bottom">
        共
        <span style="color: #1dfe8d">{{ listSize }}</span
        >支队伍 <span style="color: #f5961d">{{ personSum }}</span
        >人
      </div>
    </div>
    <!--   临时放gis弹窗示例用   -->
    <!-- <pop-team-detail></pop-team-detail> -->
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
import { emergencySever } from "@/api/installServer";
import YjwzfbStore from "@/store/wsyj/YjdwfbModule/YjdwfbStore";
import axios from "axios";
import qs from "qs";
import PopTeamDetail from "@/components/common/gisPop/PopTeamDetail.vue";
import { messsageBus } from "../../util/message";
import MapCommon from "@/util/MapCommon";
@Component({
  name: "LayoutSidebar",
  components: {
    PopTeamDetail
  },
  mixins: [MapCommon] // GIS 将地图解析方法混入当前组件
})
export default class LayoutSidebar extends Vue {
  private intervals: any = null;
  private ifShow = true;
  private searchValue = "";
  private loading = true;
  private currentLi = -1;
  private teamList = [];
  private showList: any[] = [];
  private MapComp: any = null;
  private tempStr = "";
  private  filterLengentFlag: any = true;


  private created() {
    const that = this;
    this.getListData();
    (messsageBus as any).$on("updateListData", (event: any) => {
      this.updateListData();
    });
    clearInterval(this.intervals);
    this.intervals = setInterval(function() {
      that.getListData();
    }, 300000);
  }
  private beforeDestroy() {
    clearInterval(this.intervals);
  }

  get listSize() {
    return YjwzfbStore.state.currentData.listSize;
  }

  get personSum() {
    return YjwzfbStore.state.currentData.personSum;
  }

  // 获取列表数据
  private getListData() {
    this.loading = true;
    const data = {
      teamName: this.searchValue,
      teamType: YjwzfbStore.state.teamType
    };
    emergencySever.getEmergencyList(qs.stringify(data)).then((res: any) => {
      this.loading = false;
      if (res.data.code === 0) {
        this.currentLi = -1;
        YjwzfbStore.state.currentData = res.data.data.count;
        // this.teamList = res.data.data.teamList;
        this.teamList = res.data.data.teamList.filter(
          (l: any) => l.areaflag !== null
        );
        // this.showList = res.data.data.teamList;
        this.showList = res.data.data.teamList.filter(
          (l: any) => l.areaflag !== null
        );
        this.mapLoad();
      }
    });
  }

  // 根据选中图例过滤列表数据
  private updateListData() {
    // 这句重新读取列表会影响性能，但是每次查询会保证结果都对。比如你搜索后删除搜索的弹窗，然后清空后不点击重新获取列表，就会出现看起来不对的结果 杜志勋
    this.getListData();


    // ------------------------------------------------
    const showType = YjwzfbStore.state.teamType.toString();


    this.showList = [];
    if (showType === "") {
      this.filterLengentFlag=true;
      this.showList = this.teamList;
    } else {
      this.filterLengentFlag=false;
      for (let i = 0; i < this.teamList.length; i++) {
        if (this.teamList[i]["areaflag"] === showType) {
          this.showList.push(this.teamList[i]);
        }
      }
    }

    let personCount = 0;
    for (let j = 0; j < this.showList.length; j++) {
      personCount += this.showList[j]["personnum"];
    }
    YjwzfbStore.state.currentData = {
      listSize: this.showList.length,
      personSum: personCount
    };
    this.mapLoad();
  }

  private dealWithData() {
    const mapConfig = (this as any).$ioc.resolve("mapConfig-map");
    const center = mapConfig.map.defaultExtent.center;
    for (let i = 0, len = this.showList.length; i < len; i++) {
      const item: any = this.showList[i];
      if (!item.lon) {
        item.lon = center[0] + Math.random() * 0.02;
      }
      if (!item.lat) {
        item.lat = center[1] + Math.random() * 0.02;
      }
      if (item.province === "测试") {
        item.longitude = 116 + 3 * Math.random();
        item.latitude = 39 + 3 * Math.random();
      } else {
        const locationPoint = this.geoProvinceKey(item.province);
        if (!!locationPoint) {
          item.longitude = locationPoint[0];
          item.latitude = locationPoint[1];
        } else {
          item.longitude = 116 + 3 * Math.random();
          item.latitude = 39 + 3 * Math.random();
        }
      }
      item.hospsource = !!item.hospsource
        ? item.hospsource
        : g2.core.Guid.newGuid();
    }
  }

  private geoProvinceKey(key: any) {
    const data: any = {
      黑龙江: [127.9688, 45.368],
      内蒙古: [110.3467, 41.4899],
      吉林: [125.8154, 44.2584],
      北京: [116.410018, 39.909401],
      辽宁: [123.1238, 42.1216],
      河北: [114.4995, 38.1006],
      天津: [117.4219, 39.4189],
      山西: [112.3352, 37.9413],
      陕西: [109.1162, 34.2004],
      甘肃: [103.5901, 36.3043],
      宁夏: [106.3586, 38.1775],
      青海: [101.4038, 36.8207],
      新疆: [87.9236, 43.5883],
      西藏: [91.11, 29.97],
      四川: [103.9526, 30.7617],
      重庆: [108.384366, 30.439702],
      山东: [117.1582, 36.8701],
      河南: [113.4668, 34.6234],
      江苏: [118.8062, 31.9208],
      安徽: [117.29, 32.0581],
      湖北: [114.3896, 30.6628],
      浙江: [119.5313, 29.8773],
      福建: [119.4543, 25.9222],
      江西: [116.0046, 28.6633],
      湖南: [113.0823, 28.2568],
      贵州: [106.6992, 26.7682],
      云南: [102.9199, 25.4663],
      广东: [113.12244, 23.009505],
      广西: [108.479, 23.1152],
      海南: [110.3893, 19.8516],
      上海: [121.4648, 31.2891]
    };
    return data[key];
  }

  // 控制收缩展开
  private showBox() {
    this.ifShow = !this.ifShow;
  }

  // 行点击事件
  private showDetails(value: any, index: any) {
    for (let i = 0; i < this.teamList.length; i++) {
      Vue.set(this.teamList[i], "edit", false);
    }
    this.currentLi = index;
    this.MapComp.location((this.teamList[this.currentLi] as any).teamid);
  }

  // 点击编辑
  private editCurrent(value: any, index: any) {
    this.showDetails(value, index);
    if (value.edit === true) {
      Vue.set(value, "edit", false);
    } else {
      this.tempStr = this.showList[index].teamname;
      Vue.set(value, "edit", true);
    }
  }
  // 失去焦点时加校验
  private blurClass(val: any){
        if(!val.teamname){
            val.teamname=this.tempStr;
        }
  }

  // 点击定位图标
  private resetPosition() {
    this.$message("移动图标可重新定位。");
    this.MapComp.select((this.teamList[this.currentLi] as any).teamid);
  }
  // 正则表达式 判断是否包含特殊字符
  private FnContainSpecial(s: any): any {
    const containSpecial = RegExp(
      /[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/
    );
    return containSpecial.test(s);
  }

  // 保存当前改动
  private saveCurrent(value: any, event: any) {
    // 深拷贝参数data
    const data = JSON.parse(JSON.stringify(value));
    const changeValue = event.currentTarget.nextElementSibling.value;
    Vue.set(data, "teamname", changeValue);
    delete data.edit;
    const item = this.MapComp.getModifyItem();
    data.lon = item.lon;
    data.lat = item.lat; // 更新坐标位置
    console.log(data);
    console.log(this.FnContainSpecial(data.teamname));
    // if (this.FnContainSpecial(data.teamname) === true) {
    //   this.$message.error('不能包含特殊字符');
    //   this.getListData();
    //   return;
    // }
    const teamname: string = data.teamname;
    if (teamname.length === 0) {
      this.$message.error("不能为空！");
      return;
    }
    emergencySever.saveTeamInfo(data).then((res: any) => {
      if (res.data.code === 0) {
        this.$message.success("保存成功。");
        this.MapComp.save(); // 保存成功后地图操作
        Vue.set(value, "teamname", changeValue);
        for (let i = 0; i < this.teamList.length; i++) {
          Vue.set(this.teamList[i], "edit", false);
        }
      } else {
        this.$message.error("保存失败！");
      }
    });
  }

  private mapLoad() {
    (this as any).resolveMap("map").then((data: any) => {
      this.dealWithData();
      this.MapComp = this.getComponent();
      this.$store.dispatch("YjdwfbModule/yjdwfbMapEmit", this.MapComp);
      this.MapComp.on("popup", this.onPuppup, this);
      const showType =
        YjwzfbStore.state.teamType === "" ? 0 : YjwzfbStore.state.teamType;
      this.MapComp.showTeam(showType, this.showList);
    });
  }

  private onPuppup(data: any) {
    // console.log(data);
    const $vm: any = {
      el: "#" + data.containerId,
      data() {
        return {
          popData: data.data
        };
      }
    };
    const temp: any = new PopTeamDetail($vm);
    YjwzfbStore.state.showDeatil = true;
    YjwzfbStore.state.showTelCall = false;
    YjwzfbStore.state.popData = data.data;
  }

  // 获取地图功能
  private getComponent() {
    const modules = (this as any).$ioc.resolve("GISModules-map");
    const component = modules.eventSituation.getComponent("rescueTeam");
    return component;
  }
}
</script>
<style lang="less" scoped>
@import url("../../assets/css/LayoutSidebar.less");
</style>
